/**
 * Created by chen on 18/6/6.
 */
var allItems = {list:
  [{type:"饮料",name:"可口可乐",price:3,unit:"瓶",barcode:"ITEM00001"},
  {type:"饮料",name:"雪碧",price:3,unit:"瓶",barcode:"ITEM00002"},
  {type:"水果",name:"苹果",price:5.5,unit:"斤",barcode:"ITEM00003"},
  {type:"水果",name:"荔枝",price:15,unit:"斤",barcode:"ITEM00004"},
  {type:"生活用品",name:"电池",price:2,unit:"个",barcode:"ITEM00005"},
  {type:"食品",name:"方便面",price:4.5,unit:"袋",barcode:"ITEM00006"}]};

window.onload = function(){
  var tpl = document.getElementById('template_list').innerHTML;
  var inner_tpl_string = template(tpl, allItems);
  document.getElementById('shopping_list_info').innerHTML = inner_tpl_string;
  getCartListNum();

};

function addItemToCart()
{
  var barcode_id = this.event.target.id;
  var find_click_item = _.find(allItems.list, function(item){
    return item.barcode == barcode_id;
  });
  console.log(find_click_item);

  var arr_cart_list = JSON.parse(localStorage.getItem("arr_cart_list"))||[];
  console.log(arr_cart_list);
  if(arr_cart_list.length == 0)
  {
    find_click_item.count = 1;
    arr_cart_list.push(find_click_item);
  }
  else
  {
    for(var i = 0; i < arr_cart_list.length; i ++)
    {
      if(arr_cart_list[i].barcode == find_click_item.barcode)
      {
        arr_cart_list[i].count ++;
        break;
      }
      else if(i == arr_cart_list.length - 1)
      {
        find_click_item.count = 1;
        arr_cart_list.push(find_click_item);
        break;
      }
    }
  }
  localStorage.setItem("arr_cart_list",JSON.stringify(arr_cart_list));
  getCartListNum();
}